package wiz.client.activities.entrypoint;

import wiz.client.ClientFactory;
import wiz.client.activities.playgame.GameInProgressPlace;
import wiz.client.activities.selectplayers.SelectPlayersPlace;
import wiz.client.events.GameStartedEvent;
import wiz.client.model.WizGameModel;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.HasText;

public class EntryPointActivity extends AbstractActivity {

	
	private ClientFactory fClientFactory;
	private EntryPointView fView;
	private String fGameStateToken;
	
	public EntryPointActivity(ClientFactory cf){
		fClientFactory = cf;
		EntryPointView view = fClientFactory.buildEntryPointView();
		fView = view;
		registerHandlers();
	}
	
	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		panel.setWidget(fView);
		Window.scrollTo(0, 0);
		updateView();
	}

	private void updateView() {
		fView.getStartGameButtonEnabled().setEnabled(fGameStateToken != null);
		
		WizGameModel loadGameState;
		if(fGameStateToken == null){
			loadGameState = null;
		} else {
			loadGameState = fClientFactory.getGameStateStorage().loadGameState(fGameStateToken);
		}
		
		
		if(loadGameState == null ||  loadGameState.getWizPlayers().size() == 0){
			HasText[] addDisplayForPlayers = fView.addDisplayForPlayers(1);
			addDisplayForPlayers[0].setText("No Players Selected");
		} else {
			HasText[] addDisplayForPlayers = fView.addDisplayForPlayers( loadGameState.getWizPlayers().size());
			for(int i = 0; i < loadGameState.getWizPlayers().size(); i++){
				addDisplayForPlayers[i].setText(loadGameState.getWizPlayers().get(i).getName());
			}
		}
		
		
		
	}

	private void registerHandlers() {
		fView.getSelectPlayersClickHandlers().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				selectPlayersClicked();
			}
		});
		
		fView.getStartGameButtonClickHandlers().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				startGameClicked();
			}
		});
		
	}

	protected void startGameClicked() {
		if(fGameStateToken == null){
			throw new IllegalStateException();
		}
		fClientFactory.getPlaceController().goTo(new GameInProgressPlace(fGameStateToken));
		
		fClientFactory.getEventBus().fireEvent(new GameStartedEvent());
	}

	protected void selectPlayersClicked() {
		fClientFactory.getPlaceController().goTo(new SelectPlayersPlace(fGameStateToken));
	}

	public void setGameStateToken(String gameStateToken) {
		fGameStateToken = gameStateToken;
		updateView();
	}

}
